<p class="titulo" align="center"><?php echo $msg->get('AJDADOS_MSG_02') ?></p>
<p class="subtitulo" align="center"><?php echo $msg->get('FT_MSG_25') ?></p>
<div class="tabbar">
    <ul>
    <li><a href="index.php?inc=ajdados2.php&modo=material"<?php if ($_SESSION['ANAWEB']->RetornaModoExecucao() == "material") echo " class=\"tabact\""; ?>><?php echo $msg->get('Material_Teorico') ?></a></li>
    <li><a href="index.php?inc=ajdados2.php&modo=exemplo"<?php if ($_SESSION['ANAWEB']->RetornaModoExecucao() == "exemplo") echo " class=\"tabact\""; ?>><?php echo $msg->get('Exemplos_Prontos') ?></a></li>
    <li><a href="index.php?inc=ajdados2.php&modo=teclado"<?php if ($_SESSION['ANAWEB']->RetornaModoExecucao() == "teclado") echo " class=\"tabact\""; ?>><?php echo $msg->get('Entrada_Teclado') ?></a></li>
    </ul>
</div>
<div id="cas">
<?php
    if (!isset($Calcular))
    {
        if ($_SESSION['ANAWEB']->RetornaModoExecucao() == "material")
        {
            require_once("./classes/upload.php");
            $uploads = new Upload();
            $uploads->Lista("ajdados");
        }
        else if ($_SESSION['ANAWEB']->RetornaModoExecucao() == "exemplo")
        { //leitura de dados via banco de dados - modulo de exemplos e exercicios
            include "exibe_prob_ajdados2_xml.php";
        }
        else if ($_SESSION['ANAWEB']->RetornaModoExecucao() == "teclado")
        {
            if ((strlen($pontos) == 0) || !checaNumerico($pontos))
            {
?>
                <form method="post" enctype="multipart/form-data" action="index.php?inc=ajdados2.php">
                <br>
                <?php echo $msg->get('AJDADOS_MSG_07') ?><br>
                <input type="text" size='2' maxlength='2' name="pontos"><br><br>
                <input type="hidden" name="executar" value="sim">
                <input class="button" type="submit" name="Submit" value=<?php echo $msg->get('G_MSG_02')?>>
                </form>
<?php
            }
            else if ((strlen($vetx)==0) || (strlen($vetf)==0))
            {
?>
                <form method="post" enctype="multipart/form-data" action="index.php?inc=ajdados2.php">
                <br>
                <?php echo $msg->get('AJDADOS_MSG_09') ?><br>
                <table>
                <tr>
                <td><center>x</center></td><td><center>f(x)</center></td>
<?php
                for($i=0;$i<$pontos;$i++)
                {
?>
                    <tr>
                    <td><input type=text size='7' maxlength='7' name="vet[<?php echo $i ?>][0]"></td>
                    <td><input type=text size='7' maxlength='7' name="vet[<?php echo $i ?>][1]"></td>
<?php
                }
?>
                <br>
                </table>
                <?php echo $msg->get('XML_EXIBE_AJDADOS_MSG010') ?>
                <select name="grau">
<?php
                for ($i=1; $i<$pontos;$i++)
                {
?>
                <option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
                }
?>
                </select>
                <p>
                <?php echo $msg->get('Informe_X') ?><br>
                <input type="text" maxlength="5" size="5" name="calcx">
                </p>
                <input class="button" type="submit" name="Calcular" value="Calcular">
                </form>
<?php
            }
        }
    }
    else
    {
        echo minimos_ortogonais($vet, $grau, $calcx);
        if (isset($_POST['navegacao']))
        {
            echo "<form name=\"exemplos\" enctype=\"multipart/form-data\" method=\"post\">";
            echo "<script language=\"javascript\" type=\"text/javascript\">\n";
            echo "function criarLinks(value) {\n";
            echo "document.exemplos.indice.value = value;\n";
            echo "document.exemplos.action = 'index.php?inc=ajdados2.php&modo=exemplo'\n";
            echo "document.exemplos.submit();\n";
            echo "}\n";
            echo "</script>";
            echo "<input type=\"hidden\" name=\"id_bib\" value=\"".$id_bib."\">";
            echo "<input type=\"hidden\" name=\"xml_file\" value=\"".$xml_file."\">";
            echo "<input type=\"hidden\" name=\"indice\">";
            echo "</form>";
            echo $msg->get('Outros_Exemplos').":<br>";
            $objeto = new DOMDocument();
            $objeto->load($xml_file);
            $filho = $objeto->getelementsbytagname("datafitting");
            if ($filho->length > 0)
            {
                $datafit = $filho->item(0)->getelementsbytagname("datafit");
                for ($i=0; $i<$datafit->length; $i++)
                {
                    $options = $datafit->item($i)->getelementsbytagname("options");
                    if ($options->length > 0) {
                        $data = $options->item(0)->getattribute("data");
                    }
                    if ($data == "discrete")
                    {
                        if ($i != 0) echo " | ";
                        if ($i == $indice) echo "<b>";
                        echo "<a href=\"javascript:criarLinks($i)\"><u>".($i+1)."</u></a>";
                        if ($i == $indice) echo "</b>";
                    }
                }
            }
        }
    }

class Polinomio
{
    private $polinomio;

    public function __construct($grau=0)
    {
        for ($i = 0; $i < $grau; $i++)
            $this->polinomio[$i] = 0;
    }
    public function set($n,$valor)
    {
        $this->polinomio[$n] = $valor;
    }
    public function get()
    {
        return $this->polinomio;
    }
    public function soma($polinomio)
    {
        foreach ($polinomio->get() as $ind => $p)
        {
            if (isset($this->polinomio[$ind]))
                $this->polinomio[$ind] += $p;
            else
                $this->polinomio[$ind] = $p;
        }
    }
    public function mult($valor)
    {
        foreach ($this->polinomio as $ind => $p)
        {
            $this->polinomio[$ind] = $p * $valor;
        }
    }
    public function ev($valor)
    {
        $soma = 0;
        foreach ($this->polinomio as $ind => $p)
        {
            $soma+=$p * pow($valor,$ind);
        }
        return $soma;
    }
    public function cp($poli)
    {
        foreach ($poli->get() as $ind => $p)
        {
            $this->polinomio[$ind] = $p;
        }
    }
    public function str()
    {
        $str = "";
        $foi = false;
        foreach ($this->polinomio as $ind => $p)
        {
            if ($p > 0 && $foi)
            {
                $str.= " + ";
            }
            elseif ($p < 0)
            {
                $str.= " - ";
            }
            $foi = true;
            if ($p != 0)
                $str.= (($p != 1 || $ind == 0)?abs(round($p,4)):'').(($ind!=0)?("x<sup>".$ind."</sup>"):'');
        }
        if (empty($str)) $str = '0';
        return $str;
    }
}

function minimos_ortogonais($matriz, $grau, $valor)
{
    global $msg;
    $output="<p><strong>".$msg->get('Calculando_Polinomios_Ortogonais').":</strong></p>";
    $output.="<table bgcolor=\"#000000\" cellspacing=\"1\" cellpadding=\"5\">";
    for ($i = 0; $i < 2; $i++)
    {
        $output.="<tr>";
        if ($i == 0)
            $output.="<td bgcolor=\"#ffffff\"><strong>x</strong></td>";
        else
            $output.="<td bgcolor=\"#ffffff\"><strong>f(x)</strong></td>";
        for ($j = 0; $j < count($matriz); $j++)
        {
            $output.="<td bgcolor=\"#ffffff\">".$matriz[$j][$i]."</td>";
        }
        $output.="</tr>";
    }
    $output.="</table>";
    $phi[0] = new Polinomio();
    $phi[0]->set(0,1);
    $output.="<p>&phi;<sub>0</sub>=1<br>";
    $output.="&phi;<sub>i</sub>(x) = x<sup>i</sup> + &sum; &alpha;<sub>i,k</sub>&phi;<sub>k</sub> , k=0..i-1 , i=0..$grau (".$msg->get('Grau_Polinomio').")<br>";
    $output.="&alpha;<sub>i,k</sub> = -(x<sup>i</sup>,&phi;<sub>k</sub>(x))/(&phi;<sub>k</sub>(x),&phi;<sub>k</sub>(x))</p>";
    for ($i = 1 ; $i <= $grau; $i++)
    {
        $output.="<p><strong>".$msg->get('Calculando')." &phi;<sub>$i</sub>(x):</strong><br>";
        //somatorio
        $soma = new Polinomio();
        for ($k = 0; $k < $i; $k++)
        {
            $soma1 = 0;
            $soma2 = 0;
            for ($n = 0; $n < count($matriz); $n++)
            {
                $x = $matriz[$n][0];
                $aux = new Polinomio();
                $aux->set($i,1);
                $soma1+=$aux->ev($x)*$phi[$k]->ev($x);
                $soma2+=pow($phi[$k]->ev($x),2);
            }
            $output.="&alpha;<sub>$i,$k</sub>=$soma1/$soma2<br>";
            $somatorio = new Polinomio();
            $somatorio->cp($phi[$k]);
            $somatorio->mult(-$soma1/$soma2);
            $output.="&alpha;<sub>$i,$k</sub>&phi;<sub>$k</sub>=".$somatorio->str()."<br>";
            $soma->soma($somatorio);
        }
        $phi[$i] = new Polinomio($grau);
        $phi[$i]->set($i,1);
        $phi[$i]->soma($soma);
        $output.="&phi;<sub>$i</sub>(x)=".$phi[$i]->str()."</p>";
    }
    $output.="<p><strong>".$msg->get('Calculando')." a<sub>i</sub>&phi;<sub>i</sub>:</strong></p>";
    $output.="<p>a<sub>i</sub> = (f(x),&phi;<sub>i</sub>)/(&phi;<sub>i</sub>,&phi;<sub>i</sub>)</p>";
    for ($x = 0; $x <= $grau; $x++)
    {
        $soma1 = 0;
        $soma2 = 0;
        for ($n = 0; $n < count($matriz); $n++)
        {
            $soma1+=$matriz[$n][1]*$phi[$x]->ev($matriz[$n][0]);
            $soma2+=pow($phi[$x]->ev($matriz[$n][0]),2);
        }
        $termos[$x] = new Polinomio();
        $termos[$x]->cp($phi[$x]);
        $termos[$x]->mult( ($soma1/$soma2) );
        $output.="<p><strong>a<sub>$x</sub>&phi;<sub>$x</sub>:</strong><br>";
        $output.="a<sub>$x</sub> = $soma1/$soma2 = ".($soma1/$soma2)."<br>";
        $output.="&phi;<sub>$x</sub> = ".$phi[$x]->str()."<br>";
        $output.="a<sub>$x</sub>&phi;<sub>$x</sub> = ".$termos[$x]->str()."</p>";
    }
    $output.="<p><strong>".$msg->get('AJDADOS_MSG_14').$grau.":</strong><br>P(x)=";
    for ($x = 0; $x <= $grau; $x++)
    {
        if ($x > 0)
            $output.=" + ";
        $output.="a<sub>$x</sub>&phi;<sub>$x</sub>";
    }
    $output.="<br>";
    $polinomio = new Polinomio();
    foreach ($termos as $t)
    {
        $polinomio->soma($t);
    }
    $output.="P(x)=".$polinomio->str()."<br>";
    $output.="P($valor)=".$polinomio->ev($valor)."</p>";

    $dados_grafico = "0|";
    $dados_grafico .= "$grau|";
    $poly = $polinomio->get();
    for ($i=$grau;$i>=0;$i--) $dados_grafico .= ((isset($poly[$i]))?$poly[$i]:0)."|" ;
    $dados_grafico .= count($matriz)."|";
    for ($k = 0; $k < 2; $k++)
        for ($i=0;$i<count($matriz);$i++) 
            $dados_grafico .= $matriz[$i][$k]."|";
    $arquivo = gera_nome_arquivo();
    global $A_DB_TYPE, $A_DB_HOST,$A_DB_USER,$A_DB_PASS,$A_DB_DB;
    $conn = &ADONewConnection($A_DB_TYPE);
    $conn->PConnect($A_DB_HOST,$A_DB_USER,$A_DB_PASS,$A_DB_DB);
    $rs = $conn->Execute("INSERT INTO grafico(id,dados) values ('".$arquivo."','".$dados_grafico."');");
    if ($rs === false) die($msg->get('A_LANG_LOGIN_MSG5'));
    $rs->Close();
    $output.= "<p><img src=ajdados_grafico2.php?arquivo=".$arquivo." border=0 align=center width=600 height=400></p>";

    echo $output;
}
?>
</div>